

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>31.7. tokenize — Tokenizer for Python source &mdash; Python v2.7.8 documentation</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '2.7.8',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python v2.7.8 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python v2.7.8 documentation" href="../index.html" />
    <link rel="up" title="31. Python Language Services" href="language.html" />
    <link rel="next" title="31.8. tabnanny — Detection of ambiguous indentation" href="tabnanny.html" />
    <link rel="prev" title="31.6. keyword — Testing for Python keywords" href="keyword.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head>
  <body>  
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="tabnanny.html" title="31.8. tabnanny — Detection of ambiguous indentation"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="keyword.html" title="31.6. keyword — Testing for Python keywords"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="http://www.python.org/">Python</a> &raquo;</li>
        <li>
          <a href="../index.html">Python v2.7.8 documentation</a> &raquo;
        </li>

          <li><a href="index.html" >The Python Standard Library</a> &raquo;</li>
          <li><a href="language.html" accesskey="U">31. Python Language Services</a> &raquo;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="module-tokenize">
<span id="tokenize-tokenizer-for-python-source"></span><h1>31.7. <a class="reference internal" href="#module-tokenize" title="tokenize: Lexical scanner for Python source code."><tt class="xref py py-mod docutils literal"><span class="pre">tokenize</span></tt></a> &#8212; Tokenizer for Python source<a class="headerlink" href="#module-tokenize" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="http://hg.python.org/cpython/file/2.7/Lib/tokenize.py">Lib/tokenize.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-tokenize" title="tokenize: Lexical scanner for Python source code."><tt class="xref py py-mod docutils literal"><span class="pre">tokenize</span></tt></a> module provides a lexical scanner for Python source code,
implemented in Python.  The scanner in this module returns comments as tokens as
well, making it useful for implementing &#8220;pretty-printers,&#8221; including colorizers
for on-screen displays.</p>
<p>To simplify token stream handling, all <a class="reference internal" href="../reference/lexical_analysis.html#operators"><em>Operators</em></a> and <a class="reference internal" href="../reference/lexical_analysis.html#delimiters"><em>Delimiters</em></a>
tokens are returned using the generic <a class="reference internal" href="token.html#token.OP" title="token.OP"><tt class="xref py py-data docutils literal"><span class="pre">token.OP</span></tt></a> token type.  The exact
type can be determined by checking the second field (containing the actual
token string matched) of the tuple returned from
<a class="reference internal" href="#tokenize.generate_tokens" title="tokenize.generate_tokens"><tt class="xref py py-func docutils literal"><span class="pre">tokenize.generate_tokens()</span></tt></a> for the character sequence that identifies a
specific operator token.</p>
<p>The primary entry point is a <a class="reference internal" href="../glossary.html#term-generator"><em class="xref std std-term">generator</em></a>:</p>
<dl class="function">
<dt id="tokenize.generate_tokens">
<tt class="descclassname">tokenize.</tt><tt class="descname">generate_tokens</tt><big>(</big><em>readline</em><big>)</big><a class="headerlink" href="#tokenize.generate_tokens" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#tokenize.generate_tokens" title="tokenize.generate_tokens"><tt class="xref py py-func docutils literal"><span class="pre">generate_tokens()</span></tt></a> generator requires one argument, <em>readline</em>,
which must be a callable object which provides the same interface as the
<a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><tt class="xref py py-meth docutils literal"><span class="pre">readline()</span></tt></a> method of built-in file objects (see section
<a class="reference internal" href="stdtypes.html#bltin-file-objects"><em>File Objects</em></a>).  Each call to the function should return one line
of input as a string. Alternately, <em>readline</em> may be a callable object that
signals completion by raising <a class="reference internal" href="exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><tt class="xref py py-exc docutils literal"><span class="pre">StopIteration</span></tt></a>.</p>
<p>The generator produces 5-tuples with these members: the token type; the token
string; a 2-tuple <tt class="docutils literal"><span class="pre">(srow,</span> <span class="pre">scol)</span></tt> of ints specifying the row and column
where the token begins in the source; a 2-tuple <tt class="docutils literal"><span class="pre">(erow,</span> <span class="pre">ecol)</span></tt> of ints
specifying the row and column where the token ends in the source; and the
line on which the token was found.  The line passed (the last tuple item) is
the <em>logical</em> line; continuation lines are included.</p>
<p class="versionadded">
<span class="versionmodified">New in version 2.2.</span></p>
</dd></dl>

<p>An older entry point is retained for backward compatibility:</p>
<dl class="function">
<dt id="tokenize.tokenize">
<tt class="descclassname">tokenize.</tt><tt class="descname">tokenize</tt><big>(</big><em>readline</em><span class="optional">[</span>, <em>tokeneater</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#tokenize.tokenize" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#module-tokenize" title="tokenize: Lexical scanner for Python source code."><tt class="xref py py-func docutils literal"><span class="pre">tokenize()</span></tt></a> function accepts two parameters: one representing the input
stream, and one providing an output mechanism for <a class="reference internal" href="#module-tokenize" title="tokenize: Lexical scanner for Python source code."><tt class="xref py py-func docutils literal"><span class="pre">tokenize()</span></tt></a>.</p>
<p>The first parameter, <em>readline</em>, must be a callable object which provides the
same interface as the <a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><tt class="xref py py-meth docutils literal"><span class="pre">readline()</span></tt></a> method of built-in file objects (see
section <a class="reference internal" href="stdtypes.html#bltin-file-objects"><em>File Objects</em></a>).  Each call to the function should return one
line of input as a string. Alternately, <em>readline</em> may be a callable object that
signals completion by raising <a class="reference internal" href="exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><tt class="xref py py-exc docutils literal"><span class="pre">StopIteration</span></tt></a>.</p>
<p class="versionchanged">
<span class="versionmodified">Changed in version 2.5: </span>Added <a class="reference internal" href="exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><tt class="xref py py-exc docutils literal"><span class="pre">StopIteration</span></tt></a> support.</p>
<p>The second parameter, <em>tokeneater</em>, must also be a callable object.  It is
called once for each token, with five arguments, corresponding to the tuples
generated by <a class="reference internal" href="#tokenize.generate_tokens" title="tokenize.generate_tokens"><tt class="xref py py-func docutils literal"><span class="pre">generate_tokens()</span></tt></a>.</p>
</dd></dl>

<p>All constants from the <a class="reference internal" href="token.html#module-token" title="token: Constants representing terminal nodes of the parse tree."><tt class="xref py py-mod docutils literal"><span class="pre">token</span></tt></a> module are also exported from
<a class="reference internal" href="#module-tokenize" title="tokenize: Lexical scanner for Python source code."><tt class="xref py py-mod docutils literal"><span class="pre">tokenize</span></tt></a>, as are two additional token type values that might be passed to
the <em>tokeneater</em> function by <a class="reference internal" href="#module-tokenize" title="tokenize: Lexical scanner for Python source code."><tt class="xref py py-func docutils literal"><span class="pre">tokenize()</span></tt></a>:</p>
<dl class="data">
<dt id="tokenize.COMMENT">
<tt class="descclassname">tokenize.</tt><tt class="descname">COMMENT</tt><a class="headerlink" href="#tokenize.COMMENT" title="Permalink to this definition">¶</a></dt>
<dd><p>Token value used to indicate a comment.</p>
</dd></dl>

<dl class="data">
<dt id="tokenize.NL">
<tt class="descclassname">tokenize.</tt><tt class="descname">NL</tt><a class="headerlink" href="#tokenize.NL" title="Permalink to this definition">¶</a></dt>
<dd><p>Token value used to indicate a non-terminating newline.  The NEWLINE token
indicates the end of a logical line of Python code; NL tokens are generated when
a logical line of code is continued over multiple physical lines.</p>
</dd></dl>

<p>Another function is provided to reverse the tokenization process. This is useful
for creating tools that tokenize a script, modify the token stream, and write
back the modified script.</p>
<dl class="function">
<dt id="tokenize.untokenize">
<tt class="descclassname">tokenize.</tt><tt class="descname">untokenize</tt><big>(</big><em>iterable</em><big>)</big><a class="headerlink" href="#tokenize.untokenize" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts tokens back into Python source code.  The <em>iterable</em> must return
sequences with at least two elements, the token type and the token string.  Any
additional sequence elements are ignored.</p>
<p>The reconstructed script is returned as a single string.  The result is
guaranteed to tokenize back to match the input so that the conversion is
lossless and round-trips are assured.  The guarantee applies only to the token
type and token string as the spacing between tokens (column positions) may
change.</p>
<p class="versionadded">
<span class="versionmodified">New in version 2.5.</span></p>
</dd></dl>

<dl class="exception">
<dt id="tokenize.TokenError">
<em class="property">exception </em><tt class="descclassname">tokenize.</tt><tt class="descname">TokenError</tt><a class="headerlink" href="#tokenize.TokenError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when either a docstring or expression that may be split over several
lines is not completed anywhere in the file, for example:</p>
<div class="highlight-python"><pre>"""Beginning of
docstring</pre>
</div>
<p>or:</p>
<div class="highlight-python"><pre>[1,
 2,
 3</pre>
</div>
</dd></dl>

<p>Note that unclosed single-quoted strings do not cause an error to be
raised. They are tokenized as <tt class="docutils literal"><span class="pre">ERRORTOKEN</span></tt>, followed by the tokenization of
their contents.</p>
<p>Example of a script re-writer that transforms float literals into Decimal
objects:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">decistmt</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Substitute Decimals for floats in a string of statements.</span>

<span class="sd">    &gt;&gt;&gt; from decimal import Decimal</span>
<span class="sd">    &gt;&gt;&gt; s = &#39;print +21.3e-5*-.1234/81.7&#39;</span>
<span class="sd">    &gt;&gt;&gt; decistmt(s)</span>
<span class="sd">    &quot;print +Decimal (&#39;21.3e-5&#39;)*-Decimal (&#39;.1234&#39;)/Decimal (&#39;81.7&#39;)&quot;</span>

<span class="sd">    &gt;&gt;&gt; exec(s)</span>
<span class="sd">    -3.21716034272e-007</span>
<span class="sd">    &gt;&gt;&gt; exec(decistmt(s))</span>
<span class="sd">    -3.217160342717258261933904529E-7</span>

<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">result</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="n">g</span> <span class="o">=</span> <span class="n">generate_tokens</span><span class="p">(</span><span class="n">StringIO</span><span class="p">(</span><span class="n">s</span><span class="p">)</span><span class="o">.</span><span class="n">readline</span><span class="p">)</span>   <span class="c"># tokenize the string</span>
    <span class="k">for</span> <span class="n">toknum</span><span class="p">,</span> <span class="n">tokval</span><span class="p">,</span> <span class="n">_</span><span class="p">,</span> <span class="n">_</span><span class="p">,</span> <span class="n">_</span>  <span class="ow">in</span> <span class="n">g</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">toknum</span> <span class="o">==</span> <span class="n">NUMBER</span> <span class="ow">and</span> <span class="s">&#39;.&#39;</span> <span class="ow">in</span> <span class="n">tokval</span><span class="p">:</span>  <span class="c"># replace NUMBER tokens</span>
            <span class="n">result</span><span class="o">.</span><span class="n">extend</span><span class="p">([</span>
                <span class="p">(</span><span class="n">NAME</span><span class="p">,</span> <span class="s">&#39;Decimal&#39;</span><span class="p">),</span>
                <span class="p">(</span><span class="n">OP</span><span class="p">,</span> <span class="s">&#39;(&#39;</span><span class="p">),</span>
                <span class="p">(</span><span class="n">STRING</span><span class="p">,</span> <span class="nb">repr</span><span class="p">(</span><span class="n">tokval</span><span class="p">)),</span>
                <span class="p">(</span><span class="n">OP</span><span class="p">,</span> <span class="s">&#39;)&#39;</span><span class="p">)</span>
            <span class="p">])</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">result</span><span class="o">.</span><span class="n">append</span><span class="p">((</span><span class="n">toknum</span><span class="p">,</span> <span class="n">tokval</span><span class="p">))</span>
    <span class="k">return</span> <span class="n">untokenize</span><span class="p">(</span><span class="n">result</span><span class="p">)</span>
</pre></div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="keyword.html"
                        title="previous chapter">31.6. <tt class="docutils literal docutils literal docutils literal"><span class="pre">keyword</span></tt> &#8212; Testing for Python keywords</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="tabnanny.html"
                        title="next chapter">31.8. <tt class="docutils literal docutils literal docutils literal"><span class="pre">tabnanny</span></tt> &#8212; Detection of ambiguous indentation</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
  <li><a href="../bugs.html">Report a Bug</a></li>
  <li><a href="../_sources/library/tokenize.txt"
         rel="nofollow">Show Source</a></li>
</ul>

<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" size="18" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="tabnanny.html" title="31.8. tabnanny — Detection of ambiguous indentation"
             >next</a> |</li>
        <li class="right" >
          <a href="keyword.html" title="31.6. keyword — Testing for Python keywords"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="http://www.python.org/">Python</a> &raquo;</li>
        <li>
          <a href="../index.html">Python v2.7.8 documentation</a> &raquo;
        </li>

          <li><a href="index.html" >The Python Standard Library</a> &raquo;</li>
          <li><a href="language.html" >31. Python Language Services</a> &raquo;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2014, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="http://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Jun 29, 2014.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.0.7.
    </div>

  </body>
</html>